import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getClientInfo } from './client_info'
import { errors } from '../api/error'
import { getBaseWebUrl } from '@/utils/baseUrl'
import { getReqModel } from './sign'

let baseUrl = ''
if (process.env.NODE_ENV === 'production') {
  baseUrl = getBaseWebUrl() + process.env.VUE_APP_BASE_API
} else {
  baseUrl = process.env.VUE_APP_BASE_API
}

// create an axios instance
const service = axios.create({
  baseURL: baseUrl, // url = base url + request url
  timeout: 300000 // request timeout
})

service.defaults.headers.post['Content-Type'] = 'application/json'

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['Authorization'] = JSON.stringify({ 'token': store.getters.token })
    config.headers['clientInfo'] = getClientInfo()
    config.headers['userToken'] = store.getters.token
    config.headers['appName'] = window.appConfig.source
  }
  let req_model = {
    appName: '',
    format: '',
    sign: '',
    source: '',
    timestamp: new Date().getTime() + '',
    version: ''
  }

  switch (config.method) {
    case 'post':
      req_model = getReqModel(config.data)
      config.data = req_model
      break
    case 'get':
      // config.params = Object.assign(req_model, config.params)
      break
    case 'postout':
      config.method = 'post'
      req_model = getReqModel(config.data)
      config.data = req_model
      break
  }
  return config
}, error => {
  Message({
    message: '请求异常 ' + error.message,
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const res = response.data
  if (!res.code && response.status === 200) {
    return res
  }
  if (res.code && res.code === 200) {
    return res
  }
  if (res.code === '-1') {
    Message({
      message: '系统错误!',
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject('error')
  }
  if (res.code === '-500') {
    Message({
      message: res.result,
      dangerouslyUseHTMLString: true,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject('error')
  }
  if (res.code === '-300') {
    Message({
      message: res.result,
      type: 'error',
      duration: 2 * 1000
    })
    store.dispatch('FedLogOut').then(() => {
      setTimeout(() => {
        location.reload()
      }, 2 * 1000)
    })
    return Promise.reject('error')
  }
  if (res.code !== '0') {
    if (res.code !== '-112') {
      Message({
        message: exception(res.code, res.message),
        type: 'error',
        duration: 3 * 1000
      })
    }
    // 以下错误码处理需要强制退出登录状态的.
    // ---------------------------------------------
    if (res.code === '-2') {
      store.dispatch('FedLogOut').then(() => {
        location.reload()
      })
    }
    // ----------------------------------------------
    return Promise.reject({ e: 'error' })
  } else {
    return response.data
  }
}, error => {
  let code = ''
  if (error.response) {
    code = error.response.status
  } else {
    code = '网络已断开'
  }
  Message({
    message: '网络开小差(' + code + ')',
    type: 'error',
    duration: 3 * 1000
  })
  return Promise.reject(error)
})

function exception(code, message) {
  const list = errors.filter(e => {
    return e.code === code
  })
  if (list.length === 0) {
    return message
    // return '服务器开小差(' + code + ')'
  } else {
    return list[0].message
  }
}

export default service
